#include "Quadric.h"

 Quadric::Quadric(float A, float B, float C, float D, float E, float F, float G, float H, float I, float J)
 {
	 this->A = A;
	 this->B = A;
	 this->C = A;
	 this->D = A;
	 this->E = A;
	 this->F = A;
	 this->G = A;
	 this->H = A;
	 this->I = A;
	 this->J = A;
 }

 bool Quadric::intersection(Rayon &r, Intersection &i)
 {
	 float Aq = A * r.direction.x * r.direction.x +
		 B * r.direction.y * r.direction.y + 
		 C * r.direction.z  * r.direction.z  + 
		 D * r.direction.x * r.direction.y + 
		 E * r.direction.x * r.direction.z +
		 F * r.direction.y * r.direction.z;
	 
	 float Bq = 2*A * r.origine.x * r.direction.x+
		 2*B * r.origine.y * r.direction.y+
		 2*C * r.origine.z * r.direction.z +
		 D * (r.origine.x * r.direction.y + r.origine.y * r.direction.x) +
		 E *(r.origine.x * r.direction.z + r.origine.z * r.direction.x) +
		 F *(r.origine.y + r.direction.z + r.origine.z * r.direction.y) + 
		 G * r.direction.x+ H * r.direction.y+ I * r.direction.z;
		 
	 float Cq = A *r.origine.x * r.origine.x + B* r.origine.y * r.origine.y  + 
		 C * r.origine.z * r.origine.z  + D * r.origine.x * r.origine.y + 
		 E * r.origine.x * r.origine.z + F * r.origine.y * r.origine.z + 
		 G * r.origine.x + H * r.origine.y + I * r.origine.z + J ;

	float t;
	if (Aq == 0)
		t = -Cq / Bq;

	else if(Aq > 0)
	{
		if( Bq * Bq - 4 *Aq*Cq < 0)
			return false;
	}

		
	t =( - Bq - sqrtf(Bq * Bq  - 4 * Aq *Cq))/ 2/Aq;
	
	if(t < 0)
		 t =( - Bq + sqrtf(Bq * Bq - 4 * Aq * Cq))/ 2/Aq;

	i.pointInter = r.origine + t*r.direction;
	i.t = r.origine.distance(i.pointInter);
	i.normal = Vecteur(2 * A * i.pointInter.x + D * i.pointInter.y + E * i.pointInter.z + G,
		2 * B * i.pointInter.y + D * i.pointInter.x  + F * i.pointInter.z + H,
		2 * C * i.pointInter.z + E * i.pointInter.x + F * i.pointInter.y+ I);

	i.normal.normer();
	if(i.normal.pScalaire(r.direction) > 0)
		i.normal = -i.normal;
	return true;
 }